package com.ilink.ilinkcommon.service.impl.oss;

import com.ilink.ilinkcommon.service.oss.MinioService;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.http.Method;

@Slf4j
@Service
public class MinioServiceImpl implements MinioService {

    private final MinioClient minioClient;

    @Value("${ilink.minio.url}")
    private String minioUrl;

    @Value("${ilink.minio.bucketName}")
    private String bucketName;

    // 支持的文件扩展名，可以根据需要添加其他格式
    private final List<String> fileExtensions = Arrays.asList("pdf", "docx", "xlsx", "md", "txt", "zip", "tar");

    //  支持的图片拓展名
//    private final List<String> imageExtensions = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp");
    private final List<String> imageExtensions = Arrays.asList("jpg", "jpeg", "png");

    //  支持的icon拓展名
    private final List<String> iconExtensions = Arrays.asList("svg", "jpeg", "png");

    private final List<String> StudyTreeExtensions = Arrays.asList("mp4", "jpg", "png");

    public MinioServiceImpl(@Value("${ilink.minio.url}") String url,
        @Value("${ilink.minio.accessKey}") String accessKey,
        @Value("${ilink.minio.secretKey}") String secretKey) {
        this.minioClient = MinioClient.builder()
            .endpoint(url)
            .credentials(accessKey, secretKey)
            .build();
    }

    @Override
    // 上传单个文件到MinIO的方法
    public String uploadSingleFile(String folder, String fileName, MultipartFile file) {
        try {
            // 构造目标文件路径
            String objectName = folder + "/" + fileName;

            // 上传文件到 MinIO
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build()
            );

            log.info("文件 '{}' 上传到 '{}' 成功.", objectName, bucketName);

            // 返回文件的 URL
            return minioUrl + "/" + bucketName + "/" + objectName;
        } catch (Exception e) {
            log.error("上传文件到MinIO时遇到错误：", e);
            return null;
        }
    }


    // 根据后缀遍历生成预签名 URL
    @Override
    public String generatePresignedUrlWithExtension(String objectPath, String bucketName) {
        // 遍历所有支持的后缀名，生成预签名 URL
        for (String ext : imageExtensions) {
            String objectWithExtension = objectPath + "." + ext;
            try {
                return generatePresignedUrl(objectWithExtension, bucketName);
            } catch (Exception e) {
                // 失败时继续尝试下一个后缀
                log.warn("Failed to generate URL for {}. Trying next extension.", objectWithExtension, e);
            }
        }
        log.error("Failed to generate presigned URL for object with any supported extension.");
        return null;  // 如果没有生成成功，返回 null
    }

    // 直接生成预签名 URL
    @Override
    public String generatePresignedUrl(String objectName, String bucketName) {
        try {
            // 获取预签名 URL
            GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .method(Method.GET)
                .expiry(24, TimeUnit.HOURS)  // URL有效期设置为24小时
                .build();

            // 返回预签名 URL
            return minioClient.getPresignedObjectUrl(args);
        } catch (Exception e) {
            log.error("生成预签名 URL 时出错：", e);
            return null;  // 如果生成失败，返回 null
        }
    }
}
